package com.common.app.adapter.choiceArea

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.common.app.R
import com.common.app.data.bean.BaseCityModel

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：21/2/2023
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class AreaGridListAdapter(context: Context, data: List<BaseCityModel>?) :
    RecyclerView.Adapter<AreaGridListAdapter.GridViewHolder?>() {
    private val mContext: Context
    private val mData: List<BaseCityModel>?
    private var mInnerListener: InnerListener? = null

    init {
        mContext = context
        mData = data
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GridViewHolder {
        val view: View =
            LayoutInflater.from(mContext).inflate(R.layout.layout_cp_area_grid_item, parent, false)
        return GridViewHolder(view)
    }

    override fun onBindViewHolder(holder: GridViewHolder, position: Int) {
        val pos = holder.adapterPosition
        val data: BaseCityModel = mData?.get(pos) ?: return
        //设置item宽高
        val dm = mContext.resources.displayMetrics
        val screenWidth = dm.widthPixels
        val space = mContext.resources.getDimensionPixelSize(R.dimen.dp_10)
        val padding = mContext.resources.getDimensionPixelSize(R.dimen.dp_16)
        val indexBarWidth = mContext.resources.getDimensionPixelSize(R.dimen.dp_36)
        val itemWidth =
            (screenWidth - padding - space * (SPAN_COUNT - 1) - indexBarWidth) / SPAN_COUNT
        val lp = holder.container.layoutParams
        lp.width = itemWidth
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT
        holder.container.layoutParams = lp
        holder.name.text = data.name
        holder.container.setOnClickListener {
            if (mInnerListener != null) {
                mInnerListener!!.itemLocationClick(pos, data)
            }
        }
    }

    override fun getItemCount(): Int {
        return mData?.size ?: 0
    }

    class GridViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var container: FrameLayout
        var name: TextView

        init {
            container = itemView.findViewById(R.id.cp_grid_item_layout)
            name = itemView.findViewById(R.id.cp_gird_item_name)
        }
    }

    fun setInnerListener(listener: InnerListener?) {
        mInnerListener = listener
    }

    companion object {
        const val SPAN_COUNT = 3
    }
}